package com.horse.pack.common.exception;

import com.horse.pack.common.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * @author yangliu
 * @date 2024/3/22 12:04 PM
 */
@ControllerAdvice
@Slf4j
public class HorseExceptionAdvice {

    /**
     * HR线异常统一处理
     */
    @ExceptionHandler(CommonException.class)
    @ResponseBody
    public ResponseEntity<?> bindExceptionHandler(CommonException exception) {
        if (exception instanceof WarningException) {
            log.warn("[horse-pack] warning,error_code={},msg={}", exception.getCode(), exception.getMessage());
        } else if (exception instanceof NormalException) {
            log.error("[horse-pack] error-no-stack,error_code={},msg={}", exception.getCode(), exception.getMessage());
        } else if (exception instanceof StackErrorException) {
            log.error("[horse-pack] error-stack,error_code={},msg={}", exception.getCode(), exception.getMessage(), exception);
        }
        return buildResponse(exception.getCode(),exception.getMessage(), exception.getArgs());
    }

    private ResponseEntity<?> buildResponse(Integer code, String msg, Object... args) {
        msg = (Objects.isNull(args) || args.length == 0) ? msg.replaceAll("%s", "") : String.format(msg, args);

        BaseResponse baseResponse = new BaseResponse(code, msg);

        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<>(baseResponse, headers, HttpStatus.OK);
    }
}
